<?php
	
	namespace Aspic\Database;
	use Aspic as A;
	
	/**
	* WhereGroup allow making complex where sql condition
	* 
	* @Author Mallory Dessaintes <mdessaintes@gmail.com>
	* @version 1.0
	*/
	class WhereGroup {
		const SEP_AND = 'AND';
		const SEP_OR = 'OR';
		
		/**
		* @var array Contains others WhereGroup or "where array"
		*/
		protected $_nodes;
		
		protected $_separator;
		
		public function __construct(array $nodes = array(), $separator = self::SEP_AND) {
			$this->setNodes($nodes);
			$this->_separator = $separator;
		}
		
		public function setNodes(array $nodes) {
			$this->_nodes = $nodes;
		}
		
		public function addNode($node) {
			$this->_nodes[] = $node;
		}
		
		/**
		* @param Util The Util object that will be used to generate SQL
		*/
		public function getWhereString(Util $util) {
			$arrSql = array();
			
			foreach($this->_nodes as $key => $n) {
				if (!is_numeric($key)) {
					throw new A\Exception('Key cannot be a string, WhereGroup should contains in each row a "where" array');
				}
				
				if($n instanceof self) {
					$sql = $n->getWhereString($util);
				}
				else {
					$sql = $util->getWhereString($n, false);
				}
				
				if($sql) {
					$arrSql[] = $sql;
				}
			}
			
			if(count($arrSql)) {
				$sql = '('.implode(') '.$this->_separator.' (', $arrSql).')';
			}
			else {
				$sql = '';
			}
			
			return $sql;
		}
	}
	
?>